package com.loveyukari.service;

import com.loveyukari.dao.PermissionDao;
import com.loveyukari.model.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    private Map<Integer,List<Integer>> permissionAuthIdListMap;


    public void deleteAuthPermission(int authId,int permissionId){
        if (this.getAuthIdByPermission(permissionId).contains(authId)){
            permissionDao.deleteAuthPermission(authId,permissionId);
            reloadList(permissionId);
        }
    }

    public void addAuthPermission(int authId,int permissionId){
        if (!this.getAuthIdByPermission(permissionId).contains(authId)){
            Permission permission = permissionDao.selectById(permissionId);
            if (permission == null){
                return;
            }
            permissionDao.insertAuthPermission(authId,permission.getId());
            reloadList(permissionId);
        }
    }

    public List<Integer> getAuthIdByPermission(int permissionId){
        if (this.permissionAuthIdListMap == null){
            reloadMap();
        }
        List<Integer> list = this.permissionAuthIdListMap.get(permissionId);
        if (list == null){
            reloadList(permissionId);
            list = this.permissionAuthIdListMap.get(permissionId);
        }
        return list;
    }

    public void reloadMap(){
        List<Permission> list = permissionDao.selectAll();
        for (Permission permission :
                list) {
            reloadList(permission.getId());
        }
    }

    public void reloadList(int permissionId){
        if (this.permissionAuthIdListMap == null){
            this.permissionAuthIdListMap = new HashMap<>();
        }
        List<Integer> list = permissionDao.selectAuthIdByPermission(permissionId);
        this.permissionAuthIdListMap.put(permissionId,list);
    }
}
